import { ref, computed } from 'vue'

import { showConfirmDialog, showToast } from 'vant'

import type { FormInstance } from 'vant'

import type {
  UserPatient,
  AddPatientForm,
  EditPatientForm
} from '@/types/user-patient'

import {
  getUserPatientListApi,
  getPatientDetailApi,
  addPatientApi,
  editPatientApi,
  delPatientApi
} from '@/services/user-patient'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useConsultStore } from '@/stores'
import router from '@/router'

export function userPatient() {
  const userPatientList = ref<UserPatient[]>()

  const canAddUser = computed(() => {
    return (userPatientList.value && userPatientList.value.length < 6) ?? true
  })

  async function getUserPatientList() {
    const { data } = await getUserPatientListApi()
    userPatientList.value = data
  }

  return {
    userPatientList,
    canAddUser,
    getUserPatientList
  }
}

export function operatePatient(getNewDataCallBack: () => Promise<void>) {
  const showOperateDialog = ref(false)

  const operateFormRef = ref<FormInstance>()

  const initData: AddPatientForm = {
    defaultFlag: 0,
    gender: 1,
    idCard: '',
    name: ''
  }

  const operateForm = ref<AddPatientForm>({ ...initData })

  const defaultFlag = computed({
    get: () => {
      return Boolean(operateForm.value.defaultFlag)
    },
    set: (val) => {
      operateForm.value.defaultFlag = +val
    }
  })

  const isEdit = ref(false)

  async function delPatient() {
    try {
      await showConfirmDialog({
        title: '温馨提示',
        message: '是否确认删除'
      })
      await delPatientApi(operateForm.value.id!)
      await getNewDataCallBack()
      onCancelOperate()
    } catch (error) {
      console.log(error)
    }
  }

  async function onOperatePatient(orderId?: string) {
    if (orderId) {
      try {
        isEdit.value = true
        const { data } = await getPatientDetailApi(orderId)
        const { id, defaultFlag, gender, idCard, name } = data
        operateForm.value = { id, defaultFlag, gender, idCard, name }
      } catch (error) {
        console.log(error)
      }
    }
    showOperateDialog.value = true
  }

  async function onSubmitOperate() {
    try {
      await operateFormRef.value!.validate()
      const idCardGender = +operateForm.value.idCard.slice(-2, -1) % 2
      const genderFlag = idCardGender !== operateForm.value.gender
      if (genderFlag) {
        await showConfirmDialog({
          title: '温馨提示',
          message: `您输入的身份证号码与您选择的性别不符
          是否确认提交`
        })
      }

      if (isEdit.value) {
        await editPatientApi(operateForm.value as EditPatientForm)
      } else {
        await addPatientApi(operateForm.value)
      }
      await getNewDataCallBack()
      onCancelOperate()
    } catch (error) {
      console.log(error)
    }
  }

  function onCancelOperate() {
    operateForm.value = { ...initData }
    isEdit.value = false
    showOperateDialog.value = false
  }

  return {
    isEdit,
    showOperateDialog,
    operateForm,
    operateFormRef,
    defaultFlag,
    delPatient,
    onOperatePatient,
    onSubmitOperate,
    onCancelOperate
  }
}

export function select(route: RouteLocationNormalizedLoaded) {
  const consultStore = useConsultStore()
  const showNext = computed(() => route.query.isChange)

  const patientId = ref('')

  function onSetSelectPatient(id: string) {
    if (!showNext.value) return
    patientId.value = id
  }

  const onToNext = () => {
    if (!showNext.value) return
    if (!patientId.value) return showToast('请选择患者')
    consultStore.setPatient(patientId.value)
    router.push('/consult/pay')
  }

  const storePatientId = consultStore.consult.patientId

  return {
    storePatientId,
    showNext,
    patientId,
    onSetSelectPatient,
    onToNext
  }
}
